package cn.stronglink.esm27.collection.iot.devices.esm27.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.request.entity.OpenSerialPortEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.request.entity.PushSensorDataEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.ESM27ResponseMessageEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.WindEntity;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

public class GetWindRealtimeDatasReturnHandle implements IMessageHandle<ESM27ResponseMessageEntity, Object> {
	private static Logger logger = LogManager.getLogger(GetDeviceRealtimeDataReturnHandle.class.getName());
	private final static String ACTION_CODE = "GetWindRealtimeDatasReturn";
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	@Override
	public boolean isHandle(ESM27ResponseMessageEntity t) {
		if (t.getCommandCode() == 0x05 && t.getDatas().length == 28) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ESM27ResponseMessageEntity t) {
		WindEntity we = new WindEntity();
		we.setWindSpeed(ByteUtil.bytesToFloat(t.getDatas(), 0));
		we.setWinDirection(ByteUtil.bytesToFloat(t.getDatas(), 4));
		we.setTemperature(ByteUtil.bytesToFloat(t.getDatas(), 8));
		we.setHumidity(ByteUtil.bytesToFloat(t.getDatas(), 12));
		we.setPressure(ByteUtil.bytesToFloat(t.getDatas(), 16));
		we.setPm2_5(ByteUtil.bytesToFloat(t.getDatas(), 20));
		we.setNoise(ByteUtil.bytesToFloat(t.getDatas(), 24));
		we.setDeviceAddress(t.getDeviceAddress());

		// 获取打开串口的实例对象
		OpenSerialPortEntity sp = PushSensorDataEntity.getInstance().getOpenSerialPortEntity();
		if (sp != null) {
			we.setUserId(sp.getUserId());
			we.setRoomId(sp.getRoomId());
		}

		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(we);
		message.setIsSuccess(true);

		String json = JSON.toJSONString(message);
		topicSender.send(json);
		logger.info("发送获取风力实时数据到MQ完成:{}", json);
		return null;
	}

}